<script setup lang="ts">
import {ref, watch} from 'vue'
import {Column, ColumnList, ListTableProps} from '@/component/list-table/types.ts'
import {TableInstance} from 'element-plus'
import {omit} from "lodash";

const props = withDefaults(defineProps<ListTableProps>(), {
  border: true,
  // tooltipEffect: 'light',
  showOverflowTooltip: true,
})

const sortColumnList = ref<ColumnList>([])
const tableRef = ref<TableInstance>()

const refreshColumnList = () => {
  const arr: ColumnList = []
  if (props.columnList && props.columnList.length > 0) {
    props.columnList.forEach((item: Column) => {
      // arr.push(item)
      const column = { ...item }
      if (column.showOverflowTooltip === null || column.showOverflowTooltip === undefined) {
        column.showOverflowTooltip = true
      }
      // 删除 null 的 tooltipFormatter 避免 Element Plus 报错
      if ('tooltipFormatter' in column && column.tooltipFormatter === null) {
        delete column.tooltipFormatter
      }
      arr.push(column)
    })
  }
  sortColumnList.value = arr
}

watch(
    () => props.columnList,
    () => {
      refreshColumnList()
    },
    { immediate: true }
)

defineExpose({
  refreshColumnList,
  getRef: () => {
    return tableRef.value!
  }
})
</script>

<template>
  <el-table
      ref="tableRef"
      v-loading="props.loading"
      v-bind="Object.assign(omit(props, 'columnList', 'loading'), $attrs)"
  >
    <template v-if="sortColumnList && sortColumnList.length > 0">
      <el-table-column
          v-for="column in sortColumnList"
          :key="column.prop"
          v-bind="column"
      >
        <template #header>
          <slot :name="`${column.prop}TableHeader`" />
        </template>
        <template #default="scope">
          <slot :name="`${column.prop}Table`" :listTableColumn="column" v-bind="scope">
            {{ scope.row[column.prop] }}
          </slot>
        </template>
      </el-table-column>
    </template>
    <slot />
  </el-table>
</template>

<style scoped>

</style>